package com.gxuwz.eschool.fragment;
import android.content.SharedPreferences;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.gxuwz.eschool.R;
import com.gxuwz.eschool.config.SpUtil;

import java.util.Map;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link MessageFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class MessageFragment extends Fragment {
    //定义系统消息显示区域
    private TextView textView;
    //清除消息
    private Button clearButton;
    // 确保你有这些 TextView 的引用作为成员变量
    public MessageFragment() {

    }
    public static MessageFragment newInstance(String param1, String param2) {
        MessageFragment fragment = new MessageFragment();
        Bundle args = new Bundle();

        fragment.setArguments(args);
        return fragment;
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
       View view = inflater.inflate(R.layout.fragment_message, container, false);

        textView = view.findViewById(R.id.textView_messages); // 假设您的布局文件中有一个TextView来显示消息
        //清除消息
        // 找到清空按钮
        clearButton = view.findViewById(R.id.clear_button);
        // 设置按钮点击事件监听器
        clearButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                clearSharedPreferences();
                textView.setText("");
                Toast.makeText(getActivity(), "消息已清空", Toast.LENGTH_SHORT).show();
            }
        });

        displayAllMessages();//显示系统消息
        return view;
    }

    //“消息”界面列表显示系统消息
    private void displayAllMessages() {
        SpUtil spUtil = SpUtil.getInstance();
        // 获取SharedPreferences中的所有key
        Map<String, ?> allEntries = spUtil.mSharedPreferences.getAll();

        StringBuilder stringBuilder = new StringBuilder();

        for (Map.Entry<String, ?> entry : allEntries.entrySet()) {
            stringBuilder.append("ID: ").append(entry.getKey()).append("\n 内容: ").append(entry.getValue().toString()).append("\n");
        }
//         显示消息
        textView.setText(stringBuilder.toString());
    }

    //尝试从存储中取出
    private void displayAllMessages2() {
        SpUtil spUtil = SpUtil.getInstance();

    }

    //清徐消息的实现
    private void clearSharedPreferences() {
        SpUtil spUtil = SpUtil.getInstance();
        // 使用edit()来获取一个SharedPreferences.Editor对象，用于修改数据
        SharedPreferences.Editor editor = spUtil.mSharedPreferences.edit();
        // 清除所有数据
        editor.clear();
        // 应用修改
        editor.apply();
    }

}